import { Controller, Get, Post, Patch, Delete, Json, Param, Query, Body } from "@malagu/mvc/lib/node";
import { Post as PostModel } from "../entity";
import { ResponseData } from "../../common";
import { jsonFormat } from '../utils';

@Controller('api/post')
export class PostController {
    // 列表
    @Get()
    @Json()
    async index(@Query("page") page: number = 1, @Query("size") size: number = 20): Promise<ResponseData<PostModel[]>> {
        let posts: PostModel[] = await PostModel.find({
            take: size,
            skip: size * (page - 1),
            order: { id: "DESC" },
            relations: ["category"]
        });
        return jsonFormat(posts);
    }
    // 查询
    @Get(":id")
    async show(@Param('id') id: number): Promise<ResponseData<PostModel>> {
        let post: PostModel = await PostModel.findOne(id, {
            relations: ["category"]
        }) as PostModel;
        return jsonFormat(post);
    }
    // 创建
    @Post()
    async create(@Body("json") postData: string): Promise<any> {
        let post = JSON.parse(postData);
        try {
            let saved = await PostModel.save(post);
            return jsonFormat(saved);
        }
        catch(e) {
            return jsonFormat(e);
        }
    }
    // 更新
    @Patch(":id")
    async update(@Param("id") id: number, @Body("json") postData: string): Promise<any> {
        let saveData = JSON.parse(postData);
        try {
            let saved = await PostModel.update(id, saveData);
            return jsonFormat(saveData);
        }
        catch(e) {
            return jsonFormat(null, e);
        }
    }
    // 删除
    @Delete(":id")
    async delete(@Param("id") id: number): Promise<any> {
        try {
            let deleted = await PostModel.delete(id);
            return jsonFormat(deleted);
        }
        catch(e) {
            return jsonFormat(null, e);
        }
    }
}